<template>
  <div class="app-container">
    <div class="header-section">
      <div class="filter-section">
        <div class="filter-wrapper">
          <el-date-picker
            v-model="filterStartDate"
            type="date"
            placeholder="选择开始日期"
            value-format="yyyy-MM-dd"
            class="date-picker"
          />

          <el-date-picker
            v-model="filterEndDate"
            type="date"
            placeholder="选择结束日期"
            value-format="yyyy-MM-dd"
            class="date-picker"
          />

          <el-input
            v-model="filterHouseId"
            placeholder="房屋ID"
            clearable
            class="input-field"
          />

          <el-button
            type="primary"
            @click="handleSearch"
            class="search-btn"
          >
            查询
          </el-button>

          <el-button
            type="success"
            @click="showAddDebtModal = true"
            class="add-btn"
            style="margin-left: 10px;"
          >
            新增负债
          </el-button>
        </div>
      </div>
    </div>

    <div class="table-section">
      <el-table
        :data="pagedDebts"
        border
        stripe
        v-loading="loading"
        style="width: 100%"
        :header-cell-style="{ background: '#f5f7fa' }"
      >
        <el-table-column
          v-for="col in columns"
          :key="col.prop"
          :prop="col.prop"
          :label="col.label"
          :align="col.align"
          :min-width="col.minWidth"
          sortable
        >
          <template #default="scope">
            <span v-if="col.prop === 'totalAmount' || col.prop === 'monthlyAmount' || col.prop === 'remainingAmount'">
              {{ Number(scope.row[col.prop]).toLocaleString() }}
            </span>
            <span v-else-if="col.prop === 'createTime'">
              {{ formatDateTime(scope.row[col.prop]) }}
            </span>
            <span v-else-if="col.prop === 'repaymentDate'">
              {{ formatRepaymentDate(scope.row[col.prop]) }}
            </span>
            <span v-else>
              {{ scope.row[col.prop] }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" align="center" fixed="right">
          <template #default="{ row }">
            <div class="operation-buttons">
              <el-button
                type="danger"
                link
                @click="confirmDelete(row)"
                style="margin: 5px 0;"
              >
                删除
              </el-button>
              <el-button
                type="primary"
                link
                @click="showUpdateDebtModalFn(row)"
                style="margin: 5px 0;"
              >
                更新
              </el-button>
              <el-button
                type="warning"
                link
                @click="showRepayDialogFn(row)"
                style="margin: 5px 0;"
              >
                还款
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-wrapper">
        <el-pagination
          background
          :layout="'total, prev, pager, next, sizes, jumper'"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 新增负债对话框 -->
    <el-dialog
      v-model="showAddDebtModal"
      title="新增负债"
      width="500px"
      center
    >
      <el-form
        :model="form"
        label-width="100px"
        label-position="left"
        :rules="rules"
        ref="formRef"
      >
        <el-form-item label="房屋ID" prop="houseId">
          <el-input-number
            v-model="form.houseId"
            :min="0"
            controls-position="right"
          />
        </el-form-item>
        <el-form-item label="负债标题" prop="title">
          <el-input
            v-model="form.title"
            placeholder="请输入负债标题"
            clearable
          />
        </el-form-item>
        <el-form-item label="总金额（元）" prop="totalAmount">
          <el-input-number
            v-model="form.totalAmount"
            :min="0"
            :precision="2"
            controls-position="right"
          />
        </el-form-item>
        <el-form-item label="每月还款（元）" prop="monthlyAmount">
          <el-input-number
            v-model="form.monthlyAmount"
            :min="0"
            :precision="2"
            controls-position="right"
          />
        </el-form-item>
        <el-form-item label="剩余还款（元）" prop="remainingAmount">
          <el-input-number
            v-model="form.remainingAmount"
            :min="0"
            :precision="2"
            controls-position="right"
          />
        </el-form-item>
        <el-form-item label="每月还款日" prop="repaymentDate">
          <el-input-number
            v-model="form.repaymentDate"
            :min="1"
            :max="31"
            controls-position="right"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showAddDebtModal = false">取消</el-button>
          <el-button
            type="primary"
            @click="handleSubmit"
            :loading="submitting"
          >
            确认提交
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 更新负债对话框 -->
    <el-dialog
      v-model="showUpdateDebtModal"
      title="更新负债"
      width="500px"
      center
    >
      <el-form
        :model="updateForm"
        label-width="100px"
        label-position="left"
        :rules="rules"
        ref="updateFormRef"
      >
        <el-form-item label="房屋ID" prop="houseId">
          <el-input-number
            v-model="updateForm.houseId"
            :min="0"
            controls-position="right"
          />
        </el-form-item>
        <el-form-item label="负债标题" prop="title">
          <el-input
            v-model="updateForm.title"
            placeholder="请输入负债标题"
            clearable
          />
        </el-form-item>
        <el-form-item label="总金额（元）" prop="totalAmount">
          <el-input-number
            v-model="updateForm.totalAmount"
            :min="0"
            :precision="2"
            controls-position="right"
          />
        </el-form-item>
        <el-form-item label="每月还款（元）" prop="monthlyAmount">
          <el-input-number
            v-model="updateForm.monthlyAmount"
            :min="0"
            :precision="2"
            controls-position="right"
          />
        </el-form-item>
        <el-form-item label="剩余还款（元）" prop="remainingAmount">
          <el-input-number
            v-model="updateForm.remainingAmount"
            :min="0"
            :precision="2"
            controls-position="right"
          />
        </el-form-item>
        <el-form-item label="每月还款日" prop="repaymentDate">
          <el-input-number
            v-model="updateForm.repaymentDate"
            :min="1"
            :max="31"
            controls-position="right"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showUpdateDebtModal = false">取消</el-button>
          <el-button
            type="primary"
            @click="handleUpdate"
            :loading="submitting"
          >
            确认更新
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 还款对话框 -->
    <el-dialog
      v-model="showRepayDialog"
      title="还款"
      width="500px"
      center
    >
      <el-form
        :model="repayForm"
        label-width="120px"
        label-position="left"
      >
        <el-form-item label="还款方式">
          <el-select
            v-model="repayForm.paymentMethodId"
            placeholder="请选择还款方式"
          >
            <el-option label="微信" value="1" />
            <el-option label="支付宝" value="2" />
          </el-select>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showRepayDialog = false">取消</el-button>
          <el-button
            type="primary"
            @click="handleRepay"
            :loading="submitting"
          >
            确认还款
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import dayjs from 'dayjs';
import { getDebtList, addDebt, updateDebt, deleteDebt, repayDebt } from '@/api/debt';

// 表格列配置
const columns = [
  { prop: 'title', label: '负债标题', minWidth: '120px' },
  { prop: 'houseId', label: '房屋ID', align: 'center', minWidth: '100px' },
  { prop: 'totalAmount', label: '总金额（元）', align: 'right' },
  { prop: 'monthlyAmount', label: '每月还款（元）', align: 'right' },
  { prop: 'remainingAmount', label: '剩余金额（元）', align: 'right' },
  { prop: 'repaymentDate', label: '还款日期', minWidth: '120px' },
  { prop: 'createTime', label: '创建时间', minWidth: '160px' },
];

// 响应式数据
const currentPage = ref(1);
const pageSize = ref(10);
const debts = ref<any[]>([]);
const total = ref(0);
const loading = ref(false);
const filterStartDate = ref<string | null>(null);
const filterEndDate = ref<string | null>(null);
const filterHouseId = ref<number | null>(null);
const showAddDebtModal = ref(false);
const showUpdateDebtModal = ref(false);
const showRepayDialog = ref(false);
const submitting = ref(false);
const form = ref({
  houseId: null,
  title: '',
  totalAmount: null,
  monthlyAmount: null,
  remainingAmount: null,
  repaymentDate: null,
});
const updateForm = ref({
  id: null,
  houseId: null,
  title: '',
  totalAmount: null,
  monthlyAmount: null,
  remainingAmount: null,
  repaymentDate: null,
});
const repayForm = ref({
  debtId: null,
  paymentMethodId: null,
});

// 表单验证规则
const rules = {
  houseId: [{ required: true, message: '请输入房屋ID', trigger: 'blur' }],
  title: [{ required: true, message: '请输入负债标题', trigger: 'blur' }],
  totalAmount: [{ required: true, message: '请输入总金额', trigger: 'blur' }],
  monthlyAmount: [{ required: true, message: '请输入每月还款', trigger: 'blur' }],
  remainingAmount: [{ required: true, message: '请输入剩余还款', trigger: 'blur' }],
  repaymentDate: [
    { required: true, message: '请输入每月还款日', trigger: 'blur' },
    { min: 1, max: 31, message: '还款日范围为1-31', trigger: 'blur' },
  ],
};

// 获取负债数据
const fetchDebts = async () => {
  try {
    loading.value = true;
    const params = {
      startTime: filterStartDate.value,
      endTime: filterEndDate.value,
      houseId: filterHouseId.value,
    };

    const res = await getDebtList(params);
    console.log('API Response:', res); // 打印 API 返回数据，用于调试
    if (res.data.code === 200) {
      debts.value = res.data.data || [];
      total.value = debts.value.length; // 根据前端数据计算总数据量
    } else {
      ElMessage.error(res.data.msg || '获取数据失败');
    }
  } catch (error) {
    ElMessage.error('数据加载失败');
  } finally {
    loading.value = false;
  }
};

// 格式化日期时间
const formatDateTime = (dateValue: any) => {
  if (!dateValue) return '';
  if (typeof dateValue === 'number') {
    return dayjs(dateValue).format('YYYY-MM-DD HH:mm:ss');
  }
  return dayjs(dateValue).format('YYYY-MM-DD HH:mm:ss');
};

// 格式化还款日期
const formatRepaymentDate = (dateValue: any) => {
  if (!dateValue) return '';
  // 如果 dateValue 是一个数字，表示每月几号还款
  if (typeof dateValue === 'number') {
    return `当月 ${dateValue} 号`;
  }
  // 如果 dateValue 是一个日期字符串，解析并返回每月几号
  const date = dayjs(dateValue);
  if (date.isValid()) {
    return `每月 ${date.date()} 号`;
  }
  return dateValue;
};

// 分页事件处理
const handleSizeChange = (newSize: number) => {
  pageSize.value = newSize;
  currentPage.value = 1;
};

const handleCurrentChange = (newPage: number) => {
  currentPage.value = newPage;
};

// 计算分页后的数据
const pagedDebts = computed(() => {
  if (!debts.value || debts.value.length === 0) return [];
  const startIndex = (currentPage.value - 1) * pageSize.value;
  const endIndex = startIndex + pageSize.value;
  return debts.value.slice(startIndex, endIndex);
});

// 搜索逻辑
const handleSearch = () => {
  currentPage.value = 1;
  fetchDebts();
};

// 提交新增负债
const handleSubmit = async () => {
  submitting.value = true;
  try {
    const params = {
      houseId: form.value.houseId,
      title: form.value.title,
      totalAmount: form.value.totalAmount,
      monthlyAmount: form.value.monthlyAmount,
      remainingAmount: form.value.remainingAmount,
      repaymentDate: form.value.repaymentDate,
    };

    const res = await addDebt(params);
    if (res.data.code === 200) {
      ElMessage.success('新增负债成功');
      showAddDebtModal.value = false;
      form.value = {
        houseId: null,
        title: '',
        totalAmount: null,
        monthlyAmount: null,
        remainingAmount: null,
        repaymentDate: null,
      };
      await fetchDebts();
    } else {
      ElMessage.error(res.data.msg || '新增负债失败');
    }
  } catch (error) {
    ElMessage.error('新增负债失败');
  } finally {
    submitting.value = false;
  }
};

// 显示更新负债对话框
const showUpdateDebtModalFn = (row) => {
  updateForm.value = {
    id: row.id,
    houseId: row.houseId,
    title: row.title,
    totalAmount: row.totalAmount,
    monthlyAmount: row.monthlyAmount,
    remainingAmount: row.remainingAmount,
    repaymentDate: row.repaymentDate,
  };
  showUpdateDebtModal.value = true;
};

// 更新负债
const handleUpdate = async () => {
  submitting.value = true;
  try {
    const params = {
      id: updateForm.value.id,
      houseId: updateForm.value.houseId,
      title: updateForm.value.title,
      totalAmount: updateForm.value.totalAmount,
      monthlyAmount: updateForm.value.monthlyAmount,
      remainingAmount: updateForm.value.remainingAmount,
      repaymentDate: updateForm.value.repaymentDate,
    };

    const res = await updateDebt(params);
    if (res.data.code === 200) {
      ElMessage.success('更新负债成功');
      showUpdateDebtModal.value = false;
      await fetchDebts();
    } else {
      ElMessage.error(res.data.msg || '更新负债失败');
    }
  } catch (error) {
    ElMessage.error('更新负债失败');
  } finally {
    submitting.value = false;
  }
};

// 确认删除负债
const confirmDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      '此操作将永久删除该负债，是否继续？',
      '警告',
      {
        confirmButtonText: '确认删除',
        cancelButtonText: '取消操作',
        type: 'warning',
        center: true,
        confirmButtonClass: 'el-button--danger',
      }
    );

    // 调用删除接口
    const params = {
      id: row.id,
    };
    await deleteDebt(params);

    await fetchDebts();
    ElMessage.success('删除成功');
  } catch (error) {
    ElMessage.info('取消删除');
  }
};

// 显示还款对话框
const showRepayDialogFn = (row) => {
  repayForm.value = {
    debtId: row.id,
    paymentMethodId: null,
  };
  showRepayDialog.value = true;
};

// 处理还款
const handleRepay = async () => {
  if (!repayForm.value.paymentMethodId) {
    ElMessage.error('请选择还款方式');
    return;
  }

  try {
    await ElMessageBox.confirm('确认进行还款操作吗？', '提示', {
      confirmButtonText: '确认还款',
      cancelButtonText: '取消',
      type: 'info',
      center: true,
    });

    // 调用还款接口
    const params = {
      id: repayForm.value.debtId,
      paymentMethodId: repayForm.value.paymentMethodId,
    };
    await repayDebt(params);

    // 关闭还款对话框
    showRepayDialog.value = false;

    // 重新调用查询接口
    await fetchDebts();

    ElMessage.success('还款成功');
  } catch (error) {
    // 只有在用户点击取消时才显示“取消还款”
    if (error === 'cancel') {
      ElMessage.info('取消还款');
    }
  }
};

// 初始化加载
onMounted(() => {
  fetchDebts();
});
</script>

<style lang="scss" scoped>
.app-container {
  padding: 25px;
  background: #f7f9fc;
  min-height: calc(100vh - 60px);
}

.header-section {
  display: flex;
  justify-content: space-between;
  margin-bottom: 25px;
  background: white;
  border-radius: 8px;
  padding: 15px 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);

  .filter-section {
    flex: 1;

    .filter-wrapper {
      display: flex;
      gap: 10px;
      align-items: center;

      .date-picker,
      .input-field {
        flex: 1;
        min-width: 120px;
        max-width: 180px;
      }

      .search-btn {
        margin-left: 10px;
        padding: 0 18px;
        height: 36px;
        font-size: 14px;
      }
    }
  }
}

.table-section {
  padding: 25px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);

  :deep(.el-table) {
    .el-table__row {
      height: 56px;

      &:hover {
        background-color: #f0f7ff;
      }
    }

    th {
      background-color: #f5f7fa;
      font-weight: 500;
      color: #333;
    }
  }

  .pagination-wrapper {
    margin-top: 25px;
    display: flex;
    justify-content: flex-end;

    :deep(.el-pagination) {
      .btn-prev,
      .btn-next,
      .el-pager li {
        width: 32px;
        height: 32px;
        line-height: 32px;
        font-size: 13px;
      }

      .el-pager li.active {
        background-color: #409eff;
        color: white;
      }

      .el-input {
        width: 90px;
      }
    }
  }
}

.operation-buttons {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.add-asset-dialog,
.update-asset-dialog {
  :deep(.el-dialog) {
    border-radius: 12px;

    .el-dialog__header {
      background: #f5f7fa;
      padding: 18px 25px;
      border-radius: 12px 12px 0 0;
    }

    .el-dialog__body {
      padding: 25px;
    }

    .el-form-item {
      margin-bottom: 20px;

      .el-form-item__label {
        font-weight: 500;
      }

      .el-input,
      .el-select,
      .el-input-number,
      .el-textarea {
        width: 100%;
      }
    }

    .remarks-textarea {
      textarea {
        resize: none;
      }
    }

    .dialog-footer {
      display: flex;
      justify-content: flex-end;
      gap: 15px;
      margin-top: 25px;
    }
  }
}
</style>